app.controller('AppCtrl',['$scope','$ionicLoading','BaseService','$rootScope','$ionicHistory','appFactory','orderFactory','$ionicModal',
    '$state','$cordovaBarcodeScanner','$cordovaInAppBrowser','$cordovaDevice','$cordovaGeolocation','Push','CheckVersion','$ionicPlatform','$cordovaAppVersion',
    function($scope,$ionicLoading,BaseService,$rootScope,$ionicHistory,appFactory,orderFactory,$ionicModal,
             $state,$cordovaBarcodeScanner,$cordovaInAppBrowser,$cordovaDevice,$cordovaGeolocation,Push,CheckVersion,$ionicPlatform,$cordovaAppVersion){

        $scope.isAdmin = false;

        var checkAdmin = function(){
            var urole = appFactory.getUserInfo().user.urole;
            if (urole == 2){
                $scope.isAdmin = true;
            }

        }
        $ionicPlatform.ready(function(){
            $scope.checkForUpdates();
            var notificationCallback = function(data) {
                var notification = angular.fromJson(data);
                var platform = $cordovaDevice.getPlatform();
                if('iOS' == platform){
                    notification = notification.aps;
                    Push.setBadge(0);
                }
                alert(notification.alert);
            };
            //初始化
            Push.init(notificationCallback);

            $ionicModal.fromTemplateUrl('templates/login.html', {
                scope: $scope
            }).then(function(modal) {
                $scope.modal = modal;
                if(!appFactory.isLogin()){
                    modal.show();
                }else{
                    Push.setAlias(appFactory.getUserInfo().uid);
                }
            });
        });

        //通过扫码直接完成任务
        $scope.finishMission = function(){
            $cordovaBarcodeScanner
                .scan()
                .then(function(barcodeData) {
                    //alert(JSON.stringify(barcodeData));
                    var cancelled = barcodeData.cancelled;
                    var result = JSON.parse(barcodeData.text);
                    //alert('cancelled:'+cancelled);
                    //alert('result:'+result);
                    if (!cancelled){
                        var oid = result.OID;
                        if(!oid){
                            alert('>_< 错误!\n系统无法识别该二维码!');
                            return false;
                        }
                        var operaterId = appFactory.getUserInfo().uid;
                        orderFactory.finishOrder(oid,operaterId).then(function(){
                            if(confirm('处理成功!\n是否继续?')){
                                $scope.finishMission();
                            }
                        }).catch(function(err){
                            alert('>_< 错误!\n' + err);
                        });
                    }
                });
        }

        ///*

        var options = {
            location: 'no',
            clearcache: 'yes',
            toolbar: 'no'
        };
        $scope.checkForUpdates = function() {

            //跳转至系统的浏览器中打开

            var platform = $cordovaDevice.getPlatform();
            var checkCallback = function(build){
                //alert(build);
                checkAdmin();
                CheckVersion.checkUpdate(build).then(function(downloadUrl){

                    if(!confirm('有新版本更新,是否前往更新?')){
                        return false;
                    }
                    var link = ('iOS' == platform)?downloadUrl.ios:downloadUrl.android;
                    $cordovaInAppBrowser.open(link, '_system', options).then(function(event) {}).catch(function(event) {});
                }).catch(function(err){
                    alert('当前已是最新版本~');
                });
            };
            if('iOS' == platform){
                $cordovaAppVersion.getVersionCode().then(checkCallback);
            }else{
                $cordovaAppVersion.getVersionNumber().then(checkCallback);
            }

            /*
             var deploy = new Ionic.Deploy();
             deploy.check().then(function(response) {
             // response will be true/false
             if (response) {
             $ionicLoading.hide();
             if(confirm('检测到新版本!是否下载更新!')){
             $ionicLoading.show({
             template: '正在下载更新... ...'
             });
             deploy.download().then(function () {
             alert('下载成功');
             deploy.extract().then(function () {
             // Load the updated version
             deploy.load();
             $ionicLoading.hide();
             }, function (error) {
             alert(JSON.stringify(error));
             $ionicLoading.hide();
             }, function (progress) {
             });
             }, function (error) {
             alert(JSON.stringify(error));
             $ionicLoading.hide();
             }, function (progress) {
             $ionicLoading.show();
             });
             }
             }else{
             alert('当前已是最新版本!');
             $ionicLoading.hide();
             }
             }, function(err) {
             $ionicLoading.hide();
             alert(' Unable to check for updates');
             });
             //*/
        };
        //*/

        $scope.showRanking = function() {
            //跳转至系统的浏览器中打开
            var link = 'http://61.147.75.91/demo/reportJsp/showReport.jsp?raq=/lhb.raq';
            $cordovaInAppBrowser.open(link, '_system', options).then(function(event) {}).catch(function(event) {});

        };
        //用户收账明细
        $scope.showRanking1 = function() {
            //跳转至系统的浏览器中打开
            var link = 'http://61.147.75.91/demo/reportJsp/showReport.jsp?raq=/wlyhsc.raq';
            $cordovaInAppBrowser.open(link, '_system', options).then(function(event) {}).catch(function(event) {});

        };
        //分区收账明细
        $scope.showRanking2 = function() {
            //跳转至系统的浏览器中打开
            var link = 'http://61.147.75.91/demo/reportJsp/showReport.jsp?raq=/wlfqsc.raq';
            $cordovaInAppBrowser.open(link, '_system', options).then(function(event) {}).catch(function(event) {});
        };

        $rootScope.$on('$stateChangeStart',function(){
            //$ionicHistory.clearHistory();
            if(!appFactory.isLogin()){
                $scope.modal.show();
            }

        });
        //appFactory.reload();
        /*
         var posOptions = {timeout: 10000, enableHighAccuracy: false};
         $cordovaGeolocation
         .getCurrentPosition(posOptions)
         .then(function (position) {
         var lat  = position.coords.latitude;
         var long = position.coords.longitude;
         alert('lat:'+lat);
         alert('long:'+long);
         }, function(err) {
         // error
         alert(JSON.stringify(err));
         });
         //*/


        $scope.loginData = {username:"",password:"",namenull:true,pwdnull:true};

        $scope.barscan = function(){
            $cordovaBarcodeScanner
                .scan()
                .then(function(barcodeData) {
                    //alert(JSON.stringify(barcodeData));
                    var cancelled = barcodeData.cancelled;
                    var result = JSON.parse(barcodeData.text);
                    //alert('cancelled:'+cancelled);
                    //alert('result:'+result);
                    if(!cancelled){
                        var oid = result.OID;
                        var storage = window.localStorage;
                        var uid = storage.getItem("uid");
                        if (oid){
                            var Order = AV.Object.extend("Order");
                            var orderQuery = new AV.Query(Order);
                            orderQuery.equalTo('orderid',oid);
                            orderQuery.first().then(function(res){
                                // 若打包时间比较当前时间超过一小时则不可扫码领取
                                var status = res.get('status');
                                if(status === 4000){
                                    var oneday = 1000 * 60 * 60 * 7;
                                    var oneday2 = 1000 * 60 * 60 * 8;
                                    var oneday3 = 1000 * 60 * 60 * 9;
                                    var today = new Date();
                                    today.setHours(0);
                                    today.setMinutes(0);
                                    today.setSeconds(0);
                                    today.setMilliseconds(0);
                                    today = Date.parse(today);

                                    var yesterday = Date.parse(new Date(today - oneday));
                                    var jintiane = Date.parse(new Date(today + oneday2));
                                    var jintiann = Date.parse(new Date(today + oneday3));
                                    var timestamp = Date.parse(new Date());
                                    var warehouseendtime = res.get('warehouseendtime').getTime();

                                    if ((warehouseendtime > yesterday && warehouseendtime < jintiane)&&(timestamp<jintiann)){
                                        BaseService.barscanHandle(uid,oid).then(function(res){
                                            //alert(res.msg);
                                            var r=confirm(res.msg+"\r\n是否继续扫码!");
                                            if (r==true) {
                                                $scope.barscan();
                                            }
                                        }).catch(function(err){
                                            //alert(err.msg);
                                            var r=confirm(res.msg+"\r\n是否继续扫码!");
                                            if (r==true) {
                                                $scope.barscan();
                                            }
                                        });
                                    }else{
                                        var minute = 1000 * 60;
                                        var hour = minute * 60;
                                        var twohour = hour * 2;
                                        var time = timestamp - warehouseendtime;
                                        if (time>twohour){
                                            var r=confirm("此订单领取时间已超时,不能扫码!昨日打包完成的订单9点前领取,今日打包完成的订单2小时内领取,\r\n是否继续扫码!");
                                            if (r==true) {
                                                $scope.barscan();
                                            }
                                        }else{
                                            BaseService.barscanHandle(uid,oid).then(function(res){
                                                //alert(res.msg);
                                                var r=confirm(res.msg+"\r\n是否继续扫码!");
                                                if (r==true) {
                                                    $scope.barscan();
                                                }
                                            }).catch(function(err){
                                                //alert(err.msg);
                                                var r=confirm(res.msg+"\r\n是否继续扫码!");
                                                if (r==true) {
                                                    $scope.barscan();
                                                }
                                            });
                                        }
                                    }
                                }else{
                                    BaseService.barscanHandle(uid, oid).then(function (res) {
                                        //alert(res.msg);
                                        var r = confirm(res.msg + "\r\n是否继续扫码!");
                                        if (r == true) {
                                            $scope.barscan();
                                        }
                                    }).catch(function (err) {
                                        //alert(err.msg);
                                        var r = confirm(res.msg + "\r\n是否继续扫码!");
                                        if (r == true) {
                                            $scope.barscan();
                                        }
                                    });
                                }
                            }).catch(function(err){
                                var r=confirm("没有扫描到正确的订单信息!\r\n是否继续扫码!");
                                if (r==true) {
                                    $scope.barscan();
                                }
                            });
                        }else{
                            var r=confirm("没有扫描到正确的订单信息!\r\n是否继续扫码!");
                            if (r==true) {
                                $scope.barscan();
                            }
                        }
                    }else{
                        alert('扫描异常或退出扫描');
                    }
                }, function(error) {
                    // An error occurred
                });
        };

        /**
         * 登录
         */
        $scope.doLogin = function(){
            $ionicLoading.show({});
            appFactory.doLogin($scope.loginData.username, $scope.loginData.password).then(function (res) {
                $ionicLoading.hide();
                //checkAdmin();
                Push.setAlias(appFactory.getUserInfo().uid);
                switch (parseInt(res.query2.code)){
                    case 0:
                        $scope.modal.hide();
                        window.location.reload();
                        break;
                    case 1:
                        alert("账号或密码错误");
                        break;
                    case 2:
                        alert("系统错误");
                        break;

                }
            });
        };
    }]);


